package org.nowcoder.leetcode.BTree;

import java.util.Stack;

/**
 * Title  : 112. Path Sum
 * Source : https://leetcode.cn/problems/path-sum/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-08-30
 */

public class LeetCode_112 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null) {
            return root.val == targetSum;
        }
        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
    }

    public boolean hasPathSum2(TreeNode root, int targetSum) {
        class Pair {
            TreeNode key;
            int val;

            public Pair(TreeNode key, int val) {
                this.key = key;
                this.val = val;
            }
        }
        if (root == null) return false;
        Stack<Pair> sta = new Stack<>();
        sta.push(new Pair(root, root.val));
        while (!sta.isEmpty()) {
            Pair pair = sta.pop();
            if (pair.key.left == null && pair.key.right == null && pair.val == targetSum) {
                return true;
            }
            if (pair.key.left != null) {
                sta.push(new Pair(pair.key.left, pair.key.left.val + pair.val));
            }
            if (pair.key.right != null) {
                sta.push(new Pair(pair.key.right, pair.key.right.val + pair.val));
            }
        }
        return false;
    }
}
